package com.yinhe.music.yhmusic.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.constants.Actions;
import com.yinhe.music.yhmusic.db.bean.DownloadMusicEntity;
import com.yinhe.music.yhmusic.downmusic.DownloadManager;
import com.yinhe.music.yhmusic.downmusic.IDownloadManager;
import com.yinhe.music.yhmusic.listener.OnPlayerEventListener;
import com.yinhe.music.yhmusic.manager.DialogActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.network.NetworkUtils;
import com.yinhe.music.yhmusic.play.IPlayListManager;
import com.yinhe.music.yhmusic.play.IPlayManager;
import com.yinhe.music.yhmusic.play.PlayListManager;
import com.yinhe.music.yhmusic.play.PlayManager;
import com.yinhe.music.yhmusic.receiver.NoisyAudioStreamReceiver;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 音乐播放后台服务
 *
 * @author wcy
 * @date 2015/11/27
 */
public class PlayService extends Service implements IDownloadManager, IPlayListManager, IPlayManager {

    private NoisyAudioStreamReceiver mNoisyReceiver;
    /**
     * 下载
     */
    private DownloadManager mDownloadManager;
    /**
     * 播放列表
     */
    private PlayListManager mPlayListManager;
    /**
     * 播放
     */
    private IPlayManager mPlayManager;
    /**
     * 网络监控
     */
    private NetworkUtils mNetworkUtils;

    /**
     * 接收网络状态变化回调
     *
     * @param isConnected 是否连接
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Home.NETWORK_CONNECT)
    )
    public void onRxbusNetworkStatusDidChanged(Boolean isConnected) {
        NetworkInfo info = mNetworkUtils.getNetWorkInfo();
        if (info != null
                && info.getType() == ConnectivityManager.TYPE_MOBILE
                && isPlaying()) {
            startDialog(null, DialogActivity.RESUME_PLAY);
        }
    }

    /**
     * 播放控制监听
     */
    private BroadcastReceiver mServiceBrocdcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;
            switch (action) {
                case Actions.ACTION_MEDIA_PLAY_PAUSE:
                    if (!showEmptyToast()) playPause();
                    break;
                case Actions.ACTION_MEDIA_NEXT:
                    if (!showEmptyToast()) next();
                    break;
                case Actions.ACTION_MEDIA_PREVIOUS:
                    if (!showEmptyToast()) prev();
                    break;
                default:
                    break;
            }
        }

        private boolean showEmptyToast() {
            if (!getPlayList().isEmpty() && getPlayingMusic() == null) {
                ToastUtils.show(getResources().getString(R.string.queue_is_empty));
                return true;
            }
            return false;
        }

    };


    @Override
    public void onCreate() {
        super.onCreate();
        RxBus.get().register(this);

        mDownloadManager = new DownloadManager(this);
        mPlayListManager = new PlayListManager(this);
        mPlayManager     = new PlayManager(this);
        mNetworkUtils    = new NetworkUtils(this);

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(Actions.ACTION_MEDIA_PLAY_PAUSE);
        mFilter.addAction(Actions.ACTION_MEDIA_NEXT);
        mFilter.addAction(Actions.ACTION_MEDIA_PREVIOUS);
        registerReceiver(mServiceBrocdcastReceiver, mFilter);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }

    public static void startCommand(Context context, String action) {
        Intent intent = new Intent(context, PlayService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    public class PlayBinder extends Binder {
        public PlayService getService() {
            return PlayService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case Actions.ACTION_MEDIA_PLAY_PAUSE:
                    playPause();
                    break;
                case Actions.ACTION_MEDIA_NEXT:
                    next();
                    break;
                case Actions.ACTION_MEDIA_PREVIOUS:
                    prev();
                    break;
                default:
                    break;
            }
        }
        return START_NOT_STICKY;
    }

    /**
     * 显示流量提示弹窗
     *
     * @param music 歌曲
     * @param type 播放状态
     */
    public void startDialog(Music music, int type) {
        Intent intent = new Intent(this, DialogActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("music", music);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        RxBus.get().unregister(this);
        unregisterReceiver(mServiceBrocdcastReceiver);

        if (mNetworkUtils != null) {
            mNetworkUtils.onDestory();
            mNetworkUtils = null;
        }
        if (mNoisyReceiver != null) {
            unregisterReceiver(mNoisyReceiver);
            mNoisyReceiver = null;
        }

        mDownloadManager.onDestroy();
        super.onDestroy();
    }

    /**
     * =========================Play Music====================
     */
    @Override
    public long getDuration() {
        return mPlayManager.getDuration();
    }

    @Override
    public Music getPlayingMusic() {
        return mPlayManager.getPlayingMusic();
    }

    @Override
    public void updateMusicList() {
        mPlayManager.updateMusicList();
    }

    @Override
    public int getPlayingProgress() {
        return mPlayManager.getPlayingProgress();
    }

    @Override
    public int getPlayingPosition() {
        return mPlayManager.getPlayingPosition();
    }

    @Override
    public boolean isPlaying() {
        return mPlayManager.isPlaying();
    }

    @Override
    public boolean isPause() {
        return mPlayManager.isPause();
    }


    @Override
    public void playPause() {
        mPlayManager.playPause();
    }

    @Override
    public void playAll(List<Music> mList) {
        mPlayManager.playAll(mList);
    }

    @Override
    public void playPosition(List<Music> musicList, int position) {
        UmengEventUtils.playMusic(this);
        mPlayManager.playPosition(musicList, position);
    }

    @Override
    public void playMusic(Music music) {
        mPlayManager.playMusic(music);
    }

    @Override
    public int pause() {
        return mPlayManager.pause();
    }

    @Override
    public int resume() {
        return mPlayManager.resume();
    }

    @Override
    public int next() {
        return mPlayManager.next();
    }

    @Override
    public int prev() {
        return mPlayManager.prev();
    }

    @Override
    public void stopPlaying() {
        mPlayManager.stopPlaying();
    }

    @Override
    public void seekTo(int msec) {
        mPlayManager.seekTo(msec);
    }

    @Override
    public void addOnPlayEventListener(OnPlayerEventListener listener) {
        mPlayManager.addOnPlayEventListener(listener);
    }

    @Override
    public void removePlayEventListner(OnPlayerEventListener listener) {
        mPlayManager.removePlayEventListner(listener);
    }

    /**
     * =========================PlayList ====================
     */

    @Override
    public void addMusicToPlayList(Music music, int position) {
        if (mPlayListManager != null) {
            mPlayListManager.addMusicToPlayList(music, position);
        }
    }

    @Override
    public void addMusicListToPlayList(List<Music> musicList, int position) {
        if (mPlayListManager == null) {
            return;
        }
        if (musicList.isEmpty()) {
            ToastUtils.show(R.string.add_music_null);
            return;
        }
        mPlayListManager.addMusicListToPlayList(musicList, position);
        updateMusicList();
        ToastUtils.show(R.string.add_playlist_next_play);
    }

    @Override
    public void removeMusicFromPlayList(Music music) {
        if (mPlayListManager != null) {
            mPlayListManager.removeMusicFromPlayList(music);
        }
    }

    @Override
    public void clearPlayList() {
        if (mPlayListManager != null) {
            mPlayListManager.clearPlayList();
            stopPlaying();
        }
    }

    @Override
    public boolean replacePlayList(List<Music> musicList) {
        return mPlayListManager != null && mPlayListManager.replacePlayList(musicList);
    }

    @Override
    public List<Music> getPlayList() {
        if (mPlayListManager != null) {
            return mPlayListManager.getPlayList();
        }
        return new ArrayList<>();
    }

    /**
     * =========================Dwonload ====================
     */
    @Override
    public void addDownloadTask(Music music) {
        if (mDownloadManager != null) {
            mDownloadManager.addDownloadTask(music);
        }
    }

    @Override
    public void resumeStartDownloadTask(long taskId) {
        if (mDownloadManager != null) {
            mDownloadManager.resumeStartDownloadTask(taskId);
        }
    }

    @Override
    public void pauseDownloadTask(long taskId) {
        if (mDownloadManager != null) {
            mDownloadManager.pauseDownloadTask(taskId);
        }
    }

    @Override
    public void cancelDownloadTask(long taskId) {
        if (mDownloadManager != null) {
            mDownloadManager.cancelDownloadTask(taskId);
        }
    }


    @Override
    public void startAllDownloadTask() {
        if (mDownloadManager != null) {
            mDownloadManager.startAllDownloadTask();
        }
    }

    @Override
    public void pauseAllDownloadTask() {
        if (mDownloadManager != null) {
            mDownloadManager.pauseAllDownloadTask();
        }
    }


    public List<Long> getPrepareTaskList() {
        if (mDownloadManager != null) {
            return mDownloadManager.getPrepareTaskList();
        }
        return null;
    }

    public List<DownloadMusicEntity> getDownloadingMusicTaskList() {
        if (mDownloadManager != null) {
            return mDownloadManager.getDownloadingMusicTaskList();
        }
        return null;
    }

    public DownloadMusicEntity getCurrentTask() {
        if (mDownloadManager != null) {
            return mDownloadManager.getCurrentTask();
        }
        return null;
    }
}
